#include <FileSystemObjectOsg.h>
#include <EDesignerCore.h>
#include <iostream>
#include <Functions.h>
#include <SceneViewer.h>
#include <SceneViewerFunctions.h>
#include <SceneViewer.h>
#include <ObjectInspectorDirectorOsg.h>
#include <ClassFactoryObjectOsg.h>
#include <VisitorCollectGeode.h>
#include <osgDB/WriteFile>
#include <osgDB/ReadFile>
#include <OsgClassDataSource/GeodeOsg.h>
#include <QString>
#include <ObjectInspectorDirectorOsg.h>
FileSystemObjectOsg::FileSystemObjectOsg() : FileSystemObject()
{
    m_geodeGroup = new osg::Group;
}

FileSystemObjectOsg::~FileSystemObjectOsg()
{

}

//void FileSystemObjectOsg::beforeSaveFile()
//{
//    //befor PluginOsg save file,should do these things:
//    //1, run contractItem for all the fileNode item;
//    //2, save to the ive file according to file name saved in the fileNode;
//    ObjectInspectorContractFileNodeTreeVisitor contractFileNodeVisitor;
//    osg::ref_ptr<osg::Node> modelRootNode = SceneViewer::instance()->getModelRoot();
//    modelRootNode->accept(contractFileNodeVisitor);


//}

void FileSystemObjectOsg::beforeLoadFile()
{
    //create modelrootosg,and add it to root item

//    ClassFactoryObjectOsg factoryOsg;
//    EObject* modelRootObj = factoryOsg.creatObject("ModelRootOsg");
//    EDesignerCore::instance()->getRootItemPtr()->appendRow(modelRootObj->getObjItem());

    //pasue simulation

    //cancel all selected node

    //delete all children of modelRoot, this is for reload file when program is runing
    SceneViewer::instance()->clearModelRoot();

    //load file "project/GeodeFiles/collectedGeode.ive"
    osg::Node* fileNode = osgDB::readNodeFile("project/GeodeFiles/collectedGeode.ive");
    osg::Group* fileGroup = dynamic_cast<osg::Group*>(fileNode);
    if(fileGroup != NULL)
    {
        m_geodeGroup = fileGroup;
    }
}

void FileSystemObjectOsg::beforeSaveFile()
{
    VisitorCollectGeode visitorCollectGeode;
    SceneViewer::instance()->getModelRoot()->accept(visitorCollectGeode);
    osg::ref_ptr<osg::Group> group = visitorCollectGeode.getCollectionGroup();
    osgDB::writeNodeFile(*group, "project/GeodeFiles/collectedGeode.ive");
}

void FileSystemObjectOsg::afterLoadFile()
{
    m_geodeGroup = NULL;
    ObjectInspectorDirectorOsg directorOsg;
    directorOsg.refreshItemColor();
}

void FileSystemObjectOsg::completeObjByDom(EObject *newObj, const QDomElement &domElement)
{
    GeodeOsg* geodeOsg = qobject_cast<GeodeOsg*>(newObj);
    if( geodeOsg != NULL && domElement.hasAttribute("GeodeIndex"))
    {
       QString indexStr = domElement.attribute("GeodeIndex");
       int index = indexStr.toInt();
       if(index < m_geodeGroup->getNumChildren())
       {
           osg::Node* indexNode = m_geodeGroup->getChild(index);
           if(osg::Geode* indexGeode = dynamic_cast<osg::Geode*>(indexNode))
           {
               geodeOsg->replaceOsgObject(indexGeode);
               geodeOsg->setGeodeIndex(index);
           }
       }

    }
}

